Java

您所在的位置:网站首页 遍历list 获取map中的value Java

Java

2024-06-14 13:21| 来源: 网络整理| 查看: 265

将Map集合的键值对按照指定字符串拼接后输出 使用StringJoiner类使用StringBuffer类Guava包提供的Joiner类总结

使用StringJoiner类 Map map = new HashMap(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); StringJoiner sj = new StringJoiner(","); map.forEach((key, value) -> sj.add(key + ":" + value)); String result = sj.toString(); System.out.println(result); // key1:value1,key2:value2,key3:value3 使用StringBuffer类 Map map = new HashMap(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); StringBuffer sb = new StringBuffer(); for (Map.Entry entry : map.entrySet()) { sb.append(entry.getKey()).append(":").append(entry.getValue()).append(","); } String result = sb.toString(); // 去掉最后一个逗号 if (result.endsWith(",")) { result = result.substring(0, result.length() - 1); } System.out.println(result); // key1:value1,key2:value2,key3:value3 Guava包提供的Joiner类 Map map = new HashMap(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); String result = Joiner.on(",").withKeyValueSeparator(":").join(map); System.out.println(result); // key1:value1,key2:value2,key3:value3 总结

一般情况下,效率最高的方法应该是使用StringJoiner类来实现,因为它是在Java 8中引入的,使用了较新的底层技术来提高拼接字符串的效率,而且代码简洁易懂。

其次,使用Guava包的Joiner类也是一个很好的选择,虽然相对于StringJoiner类来说效率略低一些,但是其提供了更多的拼接选项,可以更方便地实现复杂的字符串拼接操作。

最后,使用StringBuffer类来实现的效率相对较低,因为它是一个线程安全的类,每次执行拼接操作都需要进行同步,而且代码也较为冗长。但是如果需要进行线程安全的字符串拼接操作,StringBuffer仍然是一个不错的选择。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3